package cn.com.infcn.util;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by cc on 2016/12/27.
 * @author jijs
 */
public class ConfigUtils {
    private static long lastModifiedTime = 0;

    private static Properties properties = null;

    //获取本地仓库地址
    public static String getLocalRepository(ServletContext ctx){
        Properties prop = getProperties(ctx);
        String s = prop.getProperty("localRepository");
        File file = new File(s);
        if(file.exists()){
            return file.getPath();
        }else{
            return null;
        }
    }

    //远程仓库地址
    public static String getRemoteRepositoryUrl(ServletContext ctx){
        Properties prop = getProperties(ctx);
        String remoteRepositoryUrl = prop.getProperty("remoteRepositoryUrl");
        if (remoteRepositoryUrl.endsWith("/") || remoteRepositoryUrl.endsWith("\\")){
            remoteRepositoryUrl = remoteRepositoryUrl.substring(0, remoteRepositoryUrl.length()-1);
        }
        return remoteRepositoryUrl;
    }

    //临时目录
    public static String getTempFileDirector(){
        String tempFileDirector = properties.getProperty("tempFileDirector");
        File file = new File(tempFileDirector);
        if(!file.exists()){
            file.mkdirs();
        }
        return file.getAbsolutePath();
    }

    //超时时间
    public static int getHttpTimeOut(){
        String timeoutStr = properties.getProperty("httpTimeOut");
        int timeout = 20;
        try {
            timeout = Integer.parseInt(timeoutStr);
        }catch (Exception ignored){
        }
        return timeout;
    }


    public static Properties getProperties(ServletContext ctx){
        String path = ctx.getRealPath("/WEB-INF/classes/conf.properties");
        File file = new File(path);

        if(isUpdateFile(file)){
            readProperties(file);
        }

        return properties;
    }

    /**
     * 判断文件是否更新，
     * @param file 读取的properties文件
     * @return boolean 如果更新则返回true
     */
    private static boolean isUpdateFile(File file){
        if(file.exists()){
            long time = file.lastModified();
            if(time>lastModifiedTime){
                lastModifiedTime = time;
                return true;
            }
        }
        return false;
    }

    /**
     * 读取properties文件
     * @param file 读取的properties文件
     */
    private static void readProperties(File file) {
        try {
            InputStream in = new FileInputStream(file);
            Properties prop = new Properties();
            prop.load(in);
            prop.getProperty("username");

            properties = prop;
            System.out.println(properties.getProperty("localRepository"));


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
